
import requests
import json
import sys
if sys.version_info < (3, 0):
    from urlparse import urljoin  # noqa
else:
    from urllib.parse import urljoin  # noqa
    from urllib.parse import urlencode


def _chk_jsonrep(ret):
    if ret.status_code == 200:
        try:
            reptext = json.loads(ret.text)
        except expression as identifier:
            return (False, ret)
        return (True, reptext)
    else:
        return (False, ret)


class GiteeLogin:

    BASE_URL = "https://gitee.com"

    @classmethod
    def post_acctoken(cls, clientid, clientsec, usr, pwd):

        params_dic = {
            "grant_type": "password",
            "username": usr,
            "password": pwd,
            "scope": "user_info",
            "client_id": clientid,
            "client_secret": clientsec
        }
        params = urlencode(params_dic)
        furl = urljoin(cls.BASE_URL, "/oauth/token?%s") % params

        header = {
            "Content-Type": "application/x-www-form-urlencoded"
        }
        ret = requests.post(furl, headers=header)
        return _chk_jsonrep(ret)

    @classmethod
    def post_refreshtoken(cls, rftoken):
        params_dic = {
            "grant_type": "refresh_token",
            "refresh_token": rftoken
        }
        params = urlencode(params_dic)
        furl = urljoin(cls.BASE_URL, "/oauth/token?%s") % params
        ret = requests.get(furl)
        return _chk_jsonrep(ret)

    @classmethod
    def get_giteeusr(cls, acctoken):
        params_dic = {
            "access_token": acctoken
        }
        params = urlencode(params_dic)
        furl = urljoin(cls.BASE_URL, "/api/v5/user?%s") % params
        ret = requests.get(furl)
        return _chk_jsonrep(ret)
